﻿// StringConvert.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <string>
#include <codecvt>
#include <iostream>
#include <clocale>
#include <locale>
#include <vector>
std::wstring s2ws(const std::string& str)
{
	std::setlocale(LC_ALL, "");
	using convert_typeX = std::codecvt_utf8<wchar_t>;
	std::wstring_convert<convert_typeX, wchar_t> converterX;

	return converterX.from_bytes(str);
}

std::string ws2s(const std::wstring& wstr)
{
	using convert_typeX = std::codecvt_utf8<wchar_t>;
	std::wstring_convert<convert_typeX, wchar_t> converterX;

	return converterX.to_bytes(wstr);
}
void func()
{
	std::setlocale(LC_ALL, "");
	const std::wstring ws = L"hheelllloo";
	const std::locale locale("");
	using converter_type = std::codecvt<wchar_t, char, std::mbstate_t>;
	auto& converter = std::use_facet<converter_type>(locale);
	std::vector<char> to(ws.length() * converter.max_length());
	std::mbstate_t state;
	const wchar_t* from_next;
	char* to_next;
	const converter_type::result result = converter.out(state, ws.data(), ws.data() + ws.length(), from_next, &to[0], &to[0] + to.size(), to_next);
	if (result == converter_type::ok || result == converter_type::noconv) {
		const std::string s(&to[0], to_next);
		std::cout << "std::string =     " << s << std::endl;
	}
}
int main()
{
	std::string mystring = "this is the narrow string";
	std::wstring mywstring = L"this is the width string";

	std::string outstring(mywstring.begin(), mywstring.end());

	std::cout << outstring << std::endl;

	std::wstring outwstring(mystring.cbegin(), mystring.cend());

	std::wcout << outwstring << std::endl;

	//std::wstring w(L"bla");
	//std::string result;
	//for (char x : w)
	//	result += x;
	//std::cout << result << '\n';
	func();
	std::cout << ws2s(L"i am 宽字符") << std::endl;
	std::wcout << s2ws("i am 来自宽字符的窄字符") << std::endl;
	std::cin.get();

	return 0;
}